const DateUtil = require('../../utils/dateUtil.js')
const  Payment  = require('../../utils/payment.js')
import { CouponModel } from '../../models/CouponModel.js'
import { CustomerModel } from '../../models/CustomerModel.js'
import { ShopModel } from '../../models/ShopModel.js'
let Coupon = new CouponModel()
let Customer = new CustomerModel()
let Shop  =  new ShopModel()
const { default: Toast } = require('../../components/dist/toast/toast.js')

let App = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo:{},
        name:'',
        telephone:'',
        shopInfo:{},
        isVip:false,
        openId:'',
        customerId:'',
        sub_price:0,

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this._init()
    },
    onShow:function(){
        this._init()
    },
    _init:function(){
        this._getUserInfo()
        this._getShopInfo()
        this._getCustomerInfo()
     
    },
    _getOpenId:function(){
        let openId = App.globalData.openId
        this.setData({openId})
        return openId
    },
    _getUserInfo:function(){
        let that = this
         // 已经授权，可以直接调用 getUserInfo 获取头像昵称
         wx.getUserInfo({
          success(res) {
            console.log("获取用户信息成功")
            that.setData({
              userInfo: res.userInfo
            })
          },
          fail(res) {
            console.log("获取用户信息失败", res)
          }
        })
      },
    _getShopInfo: async function(){
        let shopInfo = await Shop.getShop({})
        this.setData({
            shopInfo:shopInfo[0]
        })
    },
    _getCustomerInfo:async function(){
        let customer = {
            openid: this._getOpenId()
        }
        let result = await Customer.getCustomer(customer)
        this.setData({
            isVip:result[0].vip,
            customerId:result[0]._id
        })
    },
    _inputTelephone:function(e){
        this.setData({
            telephone:e.detail
        })
    },
    _inputName:function(e){
        this.setData({
            name:e.detail
        })
    },
    // 校验手机号
    _isPhoneAvailable:function(phoneInput) {
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
        if (!myreg.test(phoneInput)) {
            return false;
        } else {
            return true;
        }
    },
    // 校验字符串为空
    _isEmpty:function(str){
        if(str == '' || str == null){
            return true
        }else{
            return false
        }
    },
    _checkSubmit:function(){
        if(this._isEmpty(this.data.name)){
            return '用户名不能为空!'
        }
        if(this._isEmpty(this.data.telephone)){
            return '手机号不能为空!'
        }
        if(!this._isPhoneAvailable(this.data.telephone)){
            return '手机号格式错误!'
        }
        return ''
    },
    confirm:function(){
        let message = this._checkSubmit()
        if(message !== ''){
            wx.showToast({
              title: message,
              icon:'none'
            })
        }else{
            this._payGo(this.data.shopInfo.vip_fee)
        }
    },
    // 为会员 生成指定张无门槛优惠券
    _createCoupons: async function(count){
        console.log('count',count)
        let coupon = {
            coupon_name:'无门槛',
            openid:this.data.openId,
            start_time: DateUtil.getDate('yyyy-MM-dd hh:mm:ss',0),
            end_time : DateUtil.getDate('yyyy-MM-dd hh:mm:ss',30),
            sub_price : parseInt(this.data.shopInfo.coupon_money),
            type: 1,
        }
        let res = await Coupon.createCoupon(coupon, this.data.shopInfo.coupon_count)
        if(res){
            this.onShow()
        }
    },
    _payGo: async function(totalPrice){
        let order = {
            body : '月度会员',
            money : totalPrice * 100,
        }
        let params = {
            url:'unifiedOrder',
            data:order
        }
        let cloud = await Payment.unifiedOrder(params)
        let pay = await Payment.Pay(cloud.result.data.payment)
        if(pay){
                Toast.success('会员开通成功!')
                let customer = {
                  vip:true,
                  username:this.data.name,
                  telephone:this.data.telephone,
                  start_time: DateUtil.getDate('yyyy-MM-dd hh:mm:ss',0),
                  end_time : DateUtil.getDate('yyyy-MM-dd hh:mm:ss',30),
              }
              await Customer.updateCustomer(customer, this.data.customerId)
              this._createCoupons(this.data.shopInfo.coupon_count)
        }else{
            Toast.fail('支付失败,未开通会员功能!')
        }
       
      },

})